package com.hnkywl.sts.service.cggl;

import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.cggl.CgdmxDao;
import com.hnkywl.sts.dao.htgl.CghtDao;
import com.hnkywl.sts.dao.htgl.HtmxDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.entity.cggl.Cgd;
import com.hnkywl.sts.entity.cggl.Cgdmx;
import com.hnkywl.sts.entity.htgl.Cght;
import com.hnkywl.sts.entity.htgl.Htmx;
import com.hnkywl.sts.entity.sys.Gg;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.service.base.BmService;
import com.hnkywl.sts.util.CalcUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhanghongping on 2016-02-03.
 */
@Service
public class CgdUploadService {

    private BmService bmService;
    private HtmxDao htmxDao;
    private CgdmxDao cgdmxDao;
    private KhDao khDao;
    private CgdDao cgdDao;
    private CghtDao cghtDao;

    @Transactional
    public String saveUploadCgd(List<Map<String, String>> listMap) throws Exception{
//        String result;
        String exception = null;
//        try {
            //1、查出所有已审批的采购合同
            return updateCghtAndCreateCgdAndCreateKh(listMap);//生成采购单和卡号
//            result = "{\"code\":\"0\",\"message\":\"入库反馈成功!\"}";
//        } catch (Exception e) {
//            exception = e.getMessage();
////            result = "{\"code\":\"1\",\"message\":\"" + e.getMessage() + "\"}";
//        }
//        return result;
    }

//    class CgdComb {
//        Cght cght;
//        List<Cgdmx> cgdmxList = new ArrayList<Cgdmx>();
//        List<Kh> khList = new ArrayList<Kh>();
//
//        CgdComb(Cght cght) {
//            this.cght = cght;
//        }
//    }

    //修改采购合同和创建采购单同时生成卡号
    private String updateCghtAndCreateCgdAndCreateKh(List<Map<String, String>> listMap) throws Exception {
        StringBuilder sb = new StringBuilder();
        int iSize = listMap.size();
//        Cght cght = null;
//        List<Cgdmx> cgdmxList = new ArrayList<Cgdmx>();
//        List<Kh> khList = new ArrayList<Kh>();
//        List<CgdComb> cgdCombs = new ArrayList<CgdComb>();
//        Map<Long, CgdComb> cgdMap = new HashMap<Long, CgdComb>();
        Map<Long, Cgd> cgdMap = new HashMap<Long, Cgd>();
        for (int i = 0; i < iSize; i++) {
            Map<String, String> jsonObj = listMap.get(i);
            String sellSubNo = (String) jsonObj.get("sellSubNo");
            if (!"null".equals(sellSubNo) && !sellSubNo.isEmpty()) {
                //仓储系统L5S0026   运营系统  L5X0026
                String R = sellSubNo.substring(2, 3);
                if (StringUtils.isNotBlank(R) && R.equals("S")) {
                    String s_1 = sellSubNo.substring(0, 2);
                    String s_2 = sellSubNo.substring(3, sellSubNo.length());
                    sellSubNo = s_1 + "X" + s_2;
                }

                Cght cght = cghtDao.findCghtByXsxtXsdh(sellSubNo);
                if (null == cght || null == cght.getId()) {
                    throw new RuntimeException("没有查询到对应的采购合同!" + sellSubNo);
                }

                String resource_serial_number_1 = (String) jsonObj.get("resource_serial_number_1");//仓储资源唯一号
                String carNo = (String) jsonObj.get("carNo");//车号
                String bindNo = (String) jsonObj.get("bindNo");//捆绑号
                String fDate = (String) jsonObj.get("fDate");//出厂日期

                // 判断是否已经保存，防止重复入库，捆包号
                Kh khTemp = this.khDao.findKhByRsn(resource_serial_number_1, bindNo);
                if (null != khTemp) {
//                    break;
                    sb.append(bindNo).append(';');
                    continue;
                }

                String number = jsonObj.get("number") == null ? "0" : (String) jsonObj.get("number");//件数
                Double weight = CalcUtils.round(Double.valueOf((String) jsonObj.get("weight")), 6);//重量
                Htmx htmx = htmxDao.findHtmxByHtAndGg(sellSubNo, cght.getId());
                Gg gg = htmx.getWzgg();
                Cgdmx cgdmx = new Cgdmx();
                cgdmx.setLastUpdated(new Date());
                cgdmx.setBhsj(CalcUtils.round(htmx.getBhsj(), 4));
                cgdmx.setHsj(CalcUtils.round(htmx.getHsj(), 4));
                cgdmx.setSjdj(CalcUtils.round(htmx.getHsj(), 4));
                cgdmx.setCcrq(fDate);
                cgdmx.setGg(gg);
                cgdmx.setXsxt_xsdh(sellSubNo);
                cgdmx.setXsxt_htbm(cght.getXsxt_htbm());
                cgdmx.setCarNo(carNo);
                cgdmx.setBindNo(bindNo);
                cgdmx.setJzfs(htmx.getJzfs());
                cgdmx.setCd(htmx.getCd());
                cgdmx.setJs(Integer.valueOf(number));
                cgdmx.setSbsl(weight);
                cgdmx.setRksl(weight);
                cgdmx.setRkjs(Integer.valueOf(number));
                cgdmx.setSsjs(Integer.valueOf(number));
                cgdmx.setSssl(weight);
                cgdmx.setCreateUser(cght.getCreateUser());
                cgdmx.setCreateDepartment(cght.getCreateDepartment());
                cgdmx.setCreateOrgan(cght.getCreateOrgan());
                cgdmx.setMxh((long) i);
                cgdmxDao.save(cgdmx);
//                cgdmxList.add(cgdmx);

                //生成卡号
                Kh kh = new Kh();
                kh.setLastUpdated(new Date());
                kh.setCd(htmx.getCd());
                kh.setKhbm(bmService.getKckhbm(cght.getCk().getId()));
                kh.setKkdsl(weight);
                kh.setRksl(weight);
                kh.setRkrq(new Date());
                kh.setSl(weight);
                kh.setWsdj(CalcUtils.round(htmx.getHsj(), 4));
                kh.setXsxt_price(CalcUtils.round(htmx.getHsj(), 4));
                kh.setCght(cght);
                kh.setCk(cght.getCk());
                kh.setJtwz(gg);
                kh.setCreateUser(cght.getCreateUser());
                kh.setSfdrjg("0");
                kh.setCreateDepartment(cght.getCreateDepartment());
                kh.setCreateOrgan(cght.getCreateOrgan());
                kh.setJs(Integer.valueOf(number));
                kh.setRkjs(Integer.valueOf(number));
                kh.setSbgs(cght.getSbgs());
                kh.setCggs(cght.getSbgs());
                kh.setGys(cght.getHzf());
                kh.setCgdmx(cgdmx);
                kh.setPxh(i);
                kh.setResource_serial_number_1(resource_serial_number_1.trim());
                kh.setCshjs(Integer.valueOf(number));
                kh.setCshsl(weight);
                kh.setJhjs(Integer.valueOf(number));
                kh.setJhsl(weight);
                kh.setRkdh(cght.getHtbm() + "-" + i);
                kh.setXsxt_xsdh(sellSubNo);
                kh.setXsxt_htbm(cght.getXsxt_htbm());
                kh.setCarNo(carNo);
                kh.setBindNo(bindNo);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                kh.setXsxt_fhrq(sdf.parse(fDate));
                kh.setSjly("0");
                khDao.save(kh);
//                khList.add(kh);

//                if (!cgdMap.containsKey(cght.getId())) {
//                    cgdMap.put(cght.getId(), new CgdComb(cght));
//                }
//                CgdComb comb = cgdMap.get(cght.getId());
//                comb.cgdmxList.add(cgdmx);
//                comb.khList.add(kh);
                if (!cgdMap.containsKey(cght.getId())) {
                    //生成采购单
                    Cgd cgd = new Cgd();
                    cgd.setLastUpdated(new Date());
                    cgd.setBz("此采购单是根据" + cght.getHtbm() + "采购合同生成!");
                    cgd.setCgsj(new Date());
                    cgd.setFhrq(new Date());
                    cgd.setJhdhrq(new Date());
//            cgd.setSerialNumber(serialNumber.trim());
                    cgd.setCreateUser(cght.getCreateUser());
                    cgd.setCreateDepartment(cght.getCreateDepartment());
                    cgd.setCreateOrgan(cght.getCreateOrgan());
                    cgd.setCggs(cght.getSbgs());
                    cgd.setCght(cght);
                    cgd.setDzck(cght.getCk());
                    cgd.setGys(cght.getHzf());
                    cgd.setCgdh(this.bmService.getCgdbm("cgrk"));
                    cgd.setCglx("cgrk");
                    cgd.setZt("ysp");
                    cgd.setSl(cght.getSl().toString());
                    cgd.setRksj(new Date());
                    cgd.setRkr(cght.getSbr());
                    cgd.setSbgs(cght.getSbgs());
                    cgd.setSbbm(cght.getSbbm());
                    cgd.setSbr(cght.getSbr());
                    cgd.setYrk(true);
                    cgd.setLj(cght.getLj());
                    cgd.setEndFlag(true);
                    cgd.setCgdmxList(new ArrayList<Cgdmx>());
                    cgd.setKhList(new ArrayList<Kh>());
                    // 采购合同Map
                    cgdMap.put(cght.getId(), cgd);
                }
                Cgd cgd = cgdMap.get(cght.getId());
                cgd.getCgdmxList().add(cgdmx);
                cgd.getKhList().add(kh);
            }
        }
//        if (cgdmxList.size() > 0) {
        for (Long key : cgdMap.keySet()) {
            Cgd cgd = cgdMap.get(key);
            cgdDao.save(cgd);

            //采购入库量够了 就自动变成状态  yly
//            Map mapItem = cghtDao.findSumWlyFromCght(cght.getId());
//            Double wly = ((BigDecimal) mapItem.get("WLY")).doubleValue();
//            Map mapItem2 = cghtDao.findSumHtslFromCght(cght.getId());
//            Double htsl = ((BigDecimal) mapItem2.get("HTSL")).doubleValue();
//            if (wly >= htsl) {
//                cght.setZt("yly");
//            }
            // 更新采购合同
            Cght cght = cgd.getCght();
            cght.setCkZt(1);
            cghtDao.save(cght);
        }
        return sb.length() == 0 ? "" : ("因重复而跳过的材料：" + sb.toString());
    }

    @Autowired
    public void setBmService(BmService bmService) {
        this.bmService = bmService;
    }

    @Autowired
    public void setHtmxDao(HtmxDao htmxDao) {
        this.htmxDao = htmxDao;
    }

    @Autowired
    public void setCgdmxDao(CgdmxDao cgdmxDao) {
        this.cgdmxDao = cgdmxDao;
    }

    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }

    @Autowired
    public void setCgdDao(CgdDao cgdDao) {
        this.cgdDao = cgdDao;
    }

    @Autowired
    public void setCghtDao(CghtDao cghtDao) {
        this.cghtDao = cghtDao;
    }
}
